`<template>
  <div class="notifications">
    <!-- 通知图标和徽章 -->
    <el-badge :value="unreadCount" :hidden="!unreadCount" class="notification-badge">
      <el-icon @click="showNotifications" class="notification-icon">
        <Bell />
      </el-icon>
    </el-badge>

    <!-- 通知抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="消息通知"
      direction="rtl"
      size="300px"
    >
      <template #header>
        <div class="drawer-header">
          <span>消息通知</span>
          <el-button 
            v-if="notifications.length > 0"
            type="primary" 
            link 
            @click="handleMarkAllRead"
          >
            全部已读
          </el-button>
        </div>
      </template>

      <!-- 通知列表 -->
      <el-scrollbar>
        <div v-if="notifications.length === 0" class="empty-notifications">
          <el-empty description="暂无通知" />
        </div>
        <div v-else class="notification-list">
          <div
            v-for="notification in notifications"
            :key="notification._id"
            class="notification-item"
            :class="{ 'unread': !notification.isRead }"
            @click="handleNotificationClick(notification)"
          >
            <el-avatar :size="40" :src="notification.sender.avatar">
              {{ notification.sender.username.charAt(0) }}
            </el-avatar>
            <div class="notification-content">
              <p class="notification-text">{{ notification.content }}</p>
              <span class="notification-time">{{ formatTime(notification.createdAt) }}</span>
            </div>
            <el-dropdown trigger="click" @command="handleCommand($event, notification)">
              <el-button class="notification-action" link>
                <el-icon><More /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="markRead">
                    标记为{{ notification.isRead ? '未读' : '已读' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除通知</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-scrollbar>
    </el-drawer>
  </div>
</template>

<script setup>
import { notificationApi } from '@/utils/api';
import { Bell, More } from '@element-plus/icons-vue';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const drawerVisible = ref(false);
const notifications = ref([]);
const unreadCount = ref(0);

// 获取通知列表
const fetchNotifications = async () => {
  try {
    const response = await notificationApi.getNotifications();
    notifications.value = response.data;
  } catch (error) {
    ElMessage.error('获取通知失败');
  }
};

// 获取未读通知数量
const fetchUnreadCount = async () => {
  try {
    const response = await notificationApi.getUnreadCount();
    unreadCount.value = response.data;
  } catch (error) {
    console.error('获取未读通知数量失败', error);
  }
};

// 显示通知抽屉
const showNotifications = () => {
  drawerVisible.value = true;
  fetchNotifications();
};

// 处理通知点击
const handleNotificationClick = async (notification) => {
  if (!notification.isRead) {
    await handleMarkRead(notification);
  }
  
  // 根据通知类型和目标类型进行导航
  const { targetType, targetId } = notification;
  let route = '';
  
  switch (targetType) {
    case 'notice':
      route = `/notice/${targetId}`;
      break;
    case 'topic':
      route = `/topic/${targetId}`;
      break;
    case 'activity':
      route = `/activity/${targetId}`;
      break;
    case 'market':
      route = `/market/${targetId}`;
      break;
    case 'post':
      route = `/post/${targetId}`;
      break;
  }
  
  if (route) {
    router.push(route);
    drawerVisible.value = false;
  }
};

// 处理通知操作
const handleCommand = async (command, notification) => {
  switch (command) {
    case 'markRead':
      await handleMarkRead(notification);
      break;
    case 'delete':
      await handleDelete(notification);
      break;
  }
};

// 标记通知为已读
const handleMarkRead = async (notification) => {
  try {
    await notificationApi.markAsRead(notification._id);
    notification.isRead = true;
    await fetchUnreadCount();
    ElMessage.success('标记已读成功');
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 标记所有通知为已读
const handleMarkAllRead = async () => {
  try {
    await notificationApi.markAllAsRead();
    notifications.value.forEach(notification => {
      notification.isRead = true;
    });
    unreadCount.value = 0;
    ElMessage.success('全部标记已读成功');
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 删除通知
const handleDelete = async (notification) => {
  try {
    await notificationApi.deleteNotification(notification._id);
    notifications.value = notifications.value.filter(n => n._id !== notification._id);
    if (!notification.isRead) {
      await fetchUnreadCount();
    }
    ElMessage.success('删除成功');
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 格式化时间
const formatTime = (date) => {
  return formatDistanceToNow(new Date(date), {
    addSuffix: true,
    locale: zhCN
  });
};

// 定期更新未读通知数量
const startPolling = () => {
  setInterval(() => {
    fetchUnreadCount();
  }, 60000); // 每分钟更新一次
};

onMounted(() => {
  fetchUnreadCount();
  startPolling();
});
</script>

<style scoped>
.notifications {
  display: inline-block;
}

.notification-badge {
  margin-right: 16px;
}

.notification-icon {
  font-size: 24px;
  cursor: pointer;
  color: #606266;
}

.notification-icon:hover {
  color: #409EFF;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.notification-list {
  padding: 0 16px;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #EBEEF5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #F5F7FA;
}

.notification-item.unread {
  background-color: #F0F9FF;
}

.notification-content {
  flex: 1;
  margin: 0 12px;
}

.notification-text {
  margin: 0;
  font-size: 14px;
  line-height: 1.4;
  color: #303133;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-action {
  padding: 0;
  margin: 0;
}

.empty-notifications {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
}
</style>`
